import re, os
from sprites import Brick


height = 20

#block format:
b_re = re.compile(r'''
(\d*?)                   # offset
\[                
   (\d*?)  (:\d*?)?        # length of block in brackets (optional health)
                  \]''',re.VERBOSE)
#vert space format:
v_re = re.compile(r'^(\d+?)(?::(\d+?))?$')
#chance format:
c_re = re.compile(r'chance\s*=\s*(\d+(?:\.\d+)?)')
def create(lvl):
    chance = 0.5
    map = []
    data = open(str(lvl)+'.map').read().split('\n')
    pos = [0,0]
    nextheight = height
    for line in data:
        vs = v_re.findall(line)
        if vs:
            pos[1]+= int(vs[0][0])
            if vs[0][1]:
                nextheight = int(vs[0][1])
            continue
        
        blocks = b_re.findall(line)
        if blocks:
            for block in blocks:
                if block[0]:
                    pos[0] += int(block[0])
                health = 1
                if block[2]:
                    health = int(block[2].strip(':'))
                b = Brick()
                b.init(pos, nextheight or height, int(block[1]),health)
                map.append(b)
                pos[0] += int(block[1])
            pos[1] += nextheight or height
            pos[0] = 0
            nextheight = 0
            continue
        ch = c_re.findall(line)
        if ch:
            print ch
            chance = float(ch[0])
        
    return chance, map
        
def has(lvl):
    return os.path.exists(str(lvl)+'.map')
    
if __name__ == '__main__':
    print create[0]
        